<template>
  <div
    class="border border-solid border-color-split rounded-md max-h-80 overflow-auto cursor-pointer hover:bg-gray-50"
    :class="[selectedDictData.length === 0 && selectedProductData.length === 0 ? 'text-center' : 'pt-2 pl-2']"
    @click="showSelect"
  >
    <a-tag v-for="el in selectedDictData" :key="el.value" color="success" class="!mr-2 !mb-2">
      {{ el.label || el.value }}
    </a-tag>
    <a-tag v-for="el in selectedProductData" :key="el.id" color="processing" class="!mr-2 !mb-2">
      {{ el.name || el.id }}
    </a-tag>
    <span
      v-if="selectedDictData.length === 0 && selectedProductData.length === 0"
      class="text-color-secondary text-lg inline-block py-7"
    >
      请点击选择商品类别或商品
    </span>
    <a-modal
      v-model:visible="visible"
      title="请选择商品类别或商品"
      :body-style="{ padding: 0 }"
      :width="1050"
      @ok="handleOk"
    >
      <div class="flex flex-row items-stretch" style="height: 600px">
        <div class="w-56 border-0 border-r border-solid border-color-split p-2">
          <a-skeleton v-if="dictLoading" active loading :avatar="false"></a-skeleton>
          <a-tree
            v-if="dictData.length"
            v-model:selectedKeys="selectedDictIds"
            v-model:checkedKeys="checkedDictIds"
            check-strictly
            :tree-data="dictData"
            :field-names="{ title: 'label', key: 'value' }"
            checkable
            block-node
            show-line
            show-icon
            default-expand-all
          >
          </a-tree>
        </div>
        <div class="flex-1 overflow-hidden px-2">
          <SlTable
            class="table-pg-px0"
            :columns="columns"
            row-key="id"
            :data-source="tableData"
            :pagination="pagination"
            :loading="tableLoading"
            :row-selection="
              checkedDictIds.checked.length > 0
                ? void 0
                : {
                    type: 'checkbox',
                    selectedRowKeys,
                    onChange,
                  }
            "
          ></SlTable>
        </div>
        <div style="width: 250px" class="flex flex-col">
          <div class="border-0 border-b border-solid border-color-split px-4 py-2">
            已选商品类别或品类({{ selectedData.length }})
          </div>
          <div class="flex-1 overflow-auto px-4">
            <div v-for="(el, i) in selectedData" :key="el.value || el.id" class="py-2 flex flex-row items-center">
              <div class="flex-1">{{ el.name || el.label || el.id || el.value }}</div>
              <div class="text-color-danger cursor-pointer" @click="removeSelected(i)">移除</div>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { nextTick, onMounted, ref, watch } from "vue";
import { DictItem, DictTypeCode } from "/@/api/main/system/models";
import { ProductFileItem } from "/@/api/main/pis/models";
import { useCURD } from "/@/hooks/useCURD";
import { Api } from "/@/api/main/pis";
import { priceRender } from "/@/utils/common";
import { message, TableProps } from "ant-design-vue";
import { getDictOptions } from "/@/api/main/system";
import { SelectOptionItem } from "/@/types/antd";
import { loopItem } from "/@/utils/treeData";

const props = defineProps<{
  value: { productCategoryList: SelectOptionItem[]; goodsList: ProductFileItem[] } | null;
}>();
const emits = defineEmits(["change"]);

const visible = ref(false);
function showSelect() {
  visible.value = true;
}
/**
 * product
 */
const columns = ref<TableProps<ProductFileItem>["columns"]>([
  // {
  //   title: "商品图片",
  //   dataIndex: "thumbnail",
  // },
  {
    title: "编码",
    dataIndex: "productCode",
  },
  {
    title: "条码",
    dataIndex: "barCode",
  },
  {
    title: "品名",
    dataIndex: "name",
  },
  {
    title: "供应商",
    dataIndex: "supplierName",
  },
  {
    title: "商品类别",
    dataIndex: "productType",
  },
  {
    title: "商城分类",
    dataIndex: "mallClass",
  },
  {
    title: "产地",
    dataIndex: "productArea",
  },
  {
    title: "规格",
    dataIndex: "specifications",
  },
  {
    title: "计量单位",
    dataIndex: "measurementUnit",
  },
  {
    title: "克重",
    dataIndex: "weight",
  },
  {
    title: "有效期标准",
    dataIndex: "validityCriteria",
  },
  {
    title: "进货价",
    dataIndex: "purchasePrice",
    customRender: priceRender,
  },
  {
    title: "售价",
    dataIndex: "price",
    customRender: priceRender,
  },
  {
    title: "批发价",
    dataIndex: "wholesalePrice",
    customRender: priceRender,
  },
  {
    title: "税率",
    dataIndex: "taxRate",
  },
  {
    title: "保存方式",
    dataIndex: "saveAs",
  },
  {
    title: "积分比率",
    dataIndex: "pointRedemptionRatio",
  },
  {
    title: "状态",
    dataIndex: "status",
  },
]);
const { pagination, tableData, tableLoading, reloadTable } = useCURD<ProductFileItem>({
  getPageUrl: Api.productFilePage,
  loadOnMounted: false,
});

let firstOpen = true;
watch(visible, async (v) => {
  if (v) {
    if (firstOpen) {
      firstOpen = false;
      const data = await getDictOptions({ typeCode: DictTypeCode.productCategory });
      dictLoading.value = false;
      if (data) {
        // loopItem(data, (item) => {
        //   item.key = item.value as number;
        // });
        dictData.value = data;
        if (data.length > 0) {
          selectedDictIds.value = [data[0].value as number];
        }
      }
    }
    triggerWatch = false;
    if (selectedDictData.value.length > 0) {
      selectedData.value = [...selectedDictData.value];
      selectedRowKeys.value = [];
      checkedDictIds.value = { checked: selectedDictData.value.map((el) => el.value as number), halfChecked: [] };
    } else if (selectedProductData.value.length > 0) {
      selectedData.value = [...selectedProductData.value];
      selectedRowKeys.value = selectedProductData.value.map((el) => el.id as number);
      checkedDictIds.value = { checked: [], halfChecked: [] };
    } else {
      selectedData.value = [];
      checkedDictIds.value = { checked: [], halfChecked: [] };
      selectedRowKeys.value = [];
    }
    nextTick(() => {
      triggerWatch = true;
    });
  }
});
/**
 * dict
 */
const selectedDictIds = ref<number[]>([]);
const dictLoading = ref(true);
const dictData = ref<SelectOptionItem[]>([]);
watch(selectedDictIds, (keys) => {
  reloadTable({ model: { productTypeId: keys.length > 0 ? keys[0] : "" } });
});
/**
 * selected
 */
const selectedDictData = ref<Partial<SelectOptionItem>[]>([]);
const selectedProductData = ref<Partial<ProductFileItem>[]>([]);
// watch(() => props.value, () => {});

const selectedRowKeys = ref<number[]>([]);
function onChange(keys: number[]) {
  const copyKeys = [...selectedRowKeys.value];
  tableData.value.forEach((product) => {
    if (keys.includes(product.id)) {
      if (!copyKeys.includes(product.id)) {
        copyKeys.push(product.id);
        selectedData.value.push(product);
      }
    } else {
      let index = copyKeys.findIndex((el) => el === product.id);
      if (index >= 0) {
        copyKeys.splice(index, 1);
      }
      index = selectedData.value.findIndex((el) => el.id === product.id);
      if (index >= 0) {
        selectedData.value.splice(index, 1);
      }
    }
  });
  selectedRowKeys.value = copyKeys;
}

const checkedDictIds = ref<{ checked: number[]; halfChecked: number[] }>({ checked: [], halfChecked: [] });
let triggerWatch = true;
watch(checkedDictIds, (val) => {
  if (!triggerWatch) return;
  if (val.checked.length > 0) {
    selectedRowKeys.value = [];
    const items: SelectOptionItem[] = [];
    loopItem(dictData.value, (item) => {
      if (val.checked.includes(item.value as number)) {
        items.push(item);
      }
    });
    selectedData.value = items;
  } else {
    selectedData.value = [];
  }
});

const selectedData = ref<Partial<ProductFileItem & SelectOptionItem>[]>([]);
function removeSelected(index) {
  const removeItems = selectedData.value.splice(index, 1);
  if (checkedDictIds.value.checked.length > 0) {
    if (removeItems[0]) {
      const index = checkedDictIds.value.checked.findIndex((id) => id === removeItems[0].value);
      if (index >= 0) {
        checkedDictIds.value.checked.splice(index, 1);
      }
    }
  } else {
    selectedRowKeys.value = selectedData.value.map((el) => el.id as number);
  }
}
/**
 *
 */
function handleOk() {
  if (selectedData.value.length === 0) {
    return message.info("请至少选择一个品类或商品");
  }
  if (checkedDictIds.value.checked.length > 0) {
    selectedDictData.value = [...selectedData.value] as SelectOptionItem[];
    selectedProductData.value = [];
  } else {
    selectedProductData.value = [...selectedData.value] as ProductFileItem[];
    selectedDictData.value = [];
  }
  emits("change", {
    goodsList: [...selectedProductData.value],
    productCategoryList: [...selectedDictData.value],
  });
  visible.value = false;
}
watch(
  () => props.value,
  (val) => {
    // console.log("=======>TypeProductFormItem value change", val);
    if (val) {
      if (val.goodsList.length > 0) {
        selectedRowKeys.value = val.goodsList.map((el) => el.id);
        selectedProductData.value = val.goodsList;
        checkedDictIds.value = { checked: [], halfChecked: [] };
        selectedDictData.value = [];
        selectedData.value = [...selectedProductData.value];
        return;
      } else if (val.productCategoryList.length > 0) {
        selectedRowKeys.value = [];
        selectedProductData.value = [];
        checkedDictIds.value = { checked: val.productCategoryList.map((el) => el.value as number), halfChecked: [] };
        selectedDictData.value = val.productCategoryList;
        selectedData.value = [...selectedDictData.value];
        return;
      }
    }
    selectedRowKeys.value = [];
    checkedDictIds.value = { checked: [], halfChecked: [] };
    selectedDictData.value = [];
    selectedProductData.value = [];
    selectedData.value = [];
  },
  { immediate: true }
);
</script>
